// DateTime类的实现文件
// 基于儒略日计算，提供高效的日期时间操作

#include "DateTime.h"
#include <cassert>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <iostream>

#ifdef _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#include <unistd.h>
#include <time.h>
#endif

namespace cytoolkit {

// ============================================================================
// Date类实现
// ============================================================================

// 构造函数
Date::Date() : julianDayNumber_(0), year_(0), month_(0), day_(0), valid_(false) {}

Date::Date(int year, int month, int day) : valid_(false) {
    if (isDateValid(year, month, day)) {
        year_ = year;
        month_ = month;
        day_ = day;
        updateJulianDay();
        valid_ = true;
    }
}

Date::Date(int julianDayNum) : julianDayNumber_(julianDayNum), valid_(true) {
    updateByJulianDay();
}

Date::Date(const struct tm& tm) : valid_(false) {
    if (tm.tm_year >= 0 && tm.tm_mon >= 0 && tm.tm_mday >= 1) {
        year_ = tm.tm_year + 1900;
        month_ = tm.tm_mon + 1;
        day_ = tm.tm_mday;
        updateJulianDay();
        valid_ = true;
    }
}

// 内部方法
void Date::updateByJulianDay() {
    // 儒略日转年-月-日算法
    // 参考：http://en.wikipedia.org/wiki/Julian_day
    int a = julianDayNumber_ + 32044;
    int b = (4 * a + 3) / 146097;
    int c = a - (146097 * b) / 4;
    int d = (4 * c + 3) / 1461;
    int e = c - (1461 * d) / 4;
    int m = (5 * e + 2) / 153;
    
    day_ = e - (153 * m + 2) / 5 + 1;
    month_ = m + 3 - 12 * (m / 10);
    year_ = 100 * b + d - 4800 + m / 10;
}

void Date::updateJulianDay() {
    // 年-月-日转儒略日算法
    int year = year_;
    int month = month_;
    
    if (month <= 2) {
        year -= 1;
        month += 12;
    }
    
    int A = year / 100;
    int B = 2 - A + A / 4;
    
    julianDayNumber_ = static_cast<int>(365.25 * (year + 4716)) + 
                      static_cast<int>(30.6001 * (month + 1)) + 
                      day_ + B - 1524;
}

bool Date::isDateValid(int year, int month, int day) const {
    if (year < 1 || year > 9999 || month < 1 || month > 12 || day < 1) {
        return false;
    }
    
    // 检查每月的天数
    static const int daysInMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int maxDays = daysInMonth[month];
    
    if (month == 2 && isLeapYear(year)) {
        maxDays = 29;
    }
    
    return day <= maxDays;
}

// 公共方法
int Date::dayOfWeek() const {
    // 星期一为1，星期日为7
    // 调整算法以正确映射儒略日到星期几
    // 2023-10-15应该返回7（星期日）
    int day = (julianDayNumber_ + 1) % 7;
    return day == 0 ? 7 : day;
}

int Date::dayOfYear() const {
    // 计算本年第一天的儒略日
    Date firstDayOfYear(year_, 1, 1);
    return julianDayNumber_ - firstDayOfYear.julianDayNumber_ + 1;
}

int Date::daysInMonth() const {
    return DateTimeUtils::daysInMonth(year_, month_);
}

Date Date::addDays(int days) const {
    if (!valid_) {
        return Date();
    }
    return Date(julianDayNumber_ + days);
}

Date Date::addMonths(int months) const {
    if (!valid_) {
        return Date();
    }
    
    int year = year_;
    int month = month_ + months;
    
    if (month <= 0) {
        // 处理负月份
        int years = (1 - month) / 12 + 1;
        year -= years;
        month += years * 12;
    } else if (month > 12) {
        // 处理超过12的月份
        int years = (month - 1) / 12;
        year += years;
        month -= years * 12;
    }
    
    // 调整日期，避免无效日期
    int maxDays = DateTimeUtils::daysInMonth(year, month);
    int day = std::min(day_, maxDays);
    
    return Date(year, month, day);
}

Date Date::addYears(int years) const {
    if (!valid_) {
        return Date();
    }
    
    int newYear = year_ + years;
    int maxDays = DateTimeUtils::daysInMonth(newYear, month_);
    int newDay = std::min(day_, maxDays);
    
    return Date(newYear, month_, newDay);
}

int64_t Date::daysTo(const Date& other) const {
    if (!valid_ || !other.valid_) {
        throw DateTimeError(DateTimeError::InvalidDate);
    }
    return static_cast<int64_t>(other.julianDayNumber_) - julianDayNumber_;
}

std::string Date::toString(const std::string& format) const {
    if (!valid_) {
        return "invalid-date";
    }
    
    std::ostringstream oss;
    
    for (size_t i = 0; i < format.size(); ++i) {
        if (i + 3 < format.size() && format[i] == 'Y' && format[i+1] == 'Y' && 
            format[i+2] == 'Y' && format[i+3] == 'Y') {
            oss << std::setw(4) << std::setfill('0') << year_;
            i += 3;
        } else if (i + 1 < format.size() && format[i] == 'Y' && format[i+1] == 'Y') {
            oss << std::setw(2) << std::setfill('0') << (year_ % 100);
            i += 1;
        } else if (i + 1 < format.size() && format[i] == 'M' && format[i+1] == 'M') {
            oss << std::setw(2) << std::setfill('0') << month_;
            i += 1;
        } else if (i + 1 < format.size() && format[i] == 'D' && format[i+1] == 'D') {
            oss << std::setw(2) << std::setfill('0') << day_;
            i += 1;
        } else {
            oss << format[i];
        }
    }
    
    return oss.str();
}

std::string Date::toISOString() const {
    return toString("YYYY-MM-DD");
}

Date Date::currentDate() {
    std::time_t now = std::time(nullptr);
    struct tm* tm_now = std::localtime(&now);
    
    if (!tm_now) {
        return Date();
    }
    
    return Date(tm_now->tm_year + 1900, tm_now->tm_mon + 1, tm_now->tm_mday);
}

Date Date::fromString(const std::string& str) {
    // 简单实现，仅支持YYYY-MM-DD格式
    if (str.size() != 10 || str[4] != '-' || str[7] != '-') {
        return Date();
    }
    
    try {
        int year = std::stoi(str.substr(0, 4));
        int month = std::stoi(str.substr(5, 2));
        int day = std::stoi(str.substr(8, 2));
        
        return Date(year, month, day);
    } catch (...) {
        return Date();
    }
}

bool Date::isLeapYear(int year) {
    return DateTimeUtils::isLeapYear(year);
}

// ============================================================================
// Time类实现
// ============================================================================

// 构造函数
Time::Time() : msecsSinceMidnight_(0), hour_(0), minute_(0), second_(0), msec_(0), valid_(false) {}

Time::Time(int hour, int minute, int second, int msec) : valid_(false) {
    if (isTimeValid(hour, minute, second, msec)) {
        hour_ = hour;
        minute_ = minute;
        second_ = second;
        msec_ = msec;
        msecsSinceMidnight_ = hour * 3600000 + minute * 60000 + second * 1000 + msec;
        valid_ = true;
    }
}

Time::Time(int msecsSinceMidnight) : msecsSinceMidnight_(msecsSinceMidnight), valid_(true) {
    if (msecsSinceMidnight < 0 || msecsSinceMidnight >= 24 * 3600 * 1000) {
        valid_ = false;
    } else {
        updateByMSecs();
    }
}

Time::Time(const struct timeval& tv) : valid_(true) {
    msecsSinceMidnight_ = tv.tv_sec % 86400 * 1000 + tv.tv_usec / 1000;
    updateByMSecs();
}

// 内部方法
void Time::updateByMSecs() {
    int totalSecs = msecsSinceMidnight_ / 1000;
    msec_ = msecsSinceMidnight_ % 1000;
    
    hour_ = totalSecs / 3600;
    totalSecs %= 3600;
    
    minute_ = totalSecs / 60;
    second_ = totalSecs % 60;
}

bool Time::isTimeValid(int hour, int minute, int second, int msec) const {
    return hour >= 0 && hour < 24 && 
           minute >= 0 && minute < 60 && 
           second >= 0 && second < 60 && 
           msec >= 0 && msec < 1000;
}

// 公共方法
Time Time::addHours(int hours) const {
    if (!valid_) {
        return Time();
    }
    
    int newMSecs = msecsSinceMidnight_ + hours * 3600000;
    // 处理跨天
    newMSecs %= 86400000;
    if (newMSecs < 0) {
        newMSecs += 86400000;
    }
    
    return Time(newMSecs);
}

Time Time::addMinutes(int minutes) const {
    if (!valid_) {
        return Time();
    }
    
    int newMSecs = msecsSinceMidnight_ + minutes * 60000;
    // 处理跨天
    newMSecs %= 86400000;
    if (newMSecs < 0) {
        newMSecs += 86400000;
    }
    
    return Time(newMSecs);
}

Time Time::addSecs(int seconds) const {
    if (!valid_) {
        return Time();
    }
    
    int newMSecs = msecsSinceMidnight_ + seconds * 1000;
    // 处理跨天
    newMSecs %= 86400000;
    if (newMSecs < 0) {
        newMSecs += 86400000;
    }
    
    return Time(newMSecs);
}

Time Time::addMSecs(int msecs) const {
    if (!valid_) {
        return Time();
    }
    
    int64_t newMSecs = static_cast<int64_t>(msecsSinceMidnight_) + msecs;
    // 处理跨天
    newMSecs %= 86400000;
    if (newMSecs < 0) {
        newMSecs += 86400000;
    }
    
    return Time(static_cast<int>(newMSecs));
}

int64_t Time::secsTo(const Time& other) const {
    if (!valid_ || !other.valid_) {
        throw DateTimeError(DateTimeError::InvalidDate);
    }
    
    int64_t diff = static_cast<int64_t>(other.msecsSinceMidnight_) - msecsSinceMidnight_;
    return diff / 1000;
}

std::string Time::toString(const std::string& format) const {
    if (!valid_) {
        return "invalid-time";
    }
    
    std::ostringstream oss;
    
    for (size_t i = 0; i < format.size(); ++i) {
        if (i + 1 < format.size() && format[i] == 'H' && format[i+1] == 'H') {
            oss << std::setw(2) << std::setfill('0') << hour_;
            i += 1;
        } else if (i + 1 < format.size() && format[i] == 'M' && format[i+1] == 'M') {
            oss << std::setw(2) << std::setfill('0') << minute_;
            i += 1;
        } else if (i + 1 < format.size() && format[i] == 'S' && format[i+1] == 'S') {
            oss << std::setw(2) << std::setfill('0') << second_;
            i += 1;
        // 支持直接的毫秒格式标记，不包含前导点
        } else if (i + 1 < format.size() && format[i] == 'm' && format[i+1] == 's') {
            oss << std::setw(3) << std::setfill('0') << msec_;
            i += 1;
        } else if (i + 2 < format.size() && format.substr(i, 3) == ".ms") {
            oss << "." << std::setw(3) << std::setfill('0') << msec_;
            i += 3; // 跳过整个 ".ms" 字符串
        } else {
            oss << format[i];
        }
    }
    
    return oss.str();
}

Time Time::currentTime() {
#ifdef _WIN32
    SYSTEMTIME st;
    GetLocalTime(&st);
    return Time(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
#else
    struct timeval tv;
    gettimeofday(&tv, nullptr);
    return Time(tv);
#endif
}

Time Time::fromString(const std::string& str) {
    // 简单实现，仅支持HH:MM:SS格式
    if (str.size() >= 8 && str[2] == ':' && str[5] == ':') {
        try {
            int hour = std::stoi(str.substr(0, 2));
            int minute = std::stoi(str.substr(3, 2));
            int second = std::stoi(str.substr(6, 2));
            int msec = 0;
            
            // 可选的毫秒部分
            if (str.size() > 9 && str[8] == '.') {
                std::string msecStr = str.substr(9, 3);
                msec = std::stoi(msecStr);
            }
            
            return Time(hour, minute, second, msec);
        } catch (...) {
            return Time();
        }
    }
    
    return Time();
}

// ============================================================================
// TimeZone类实现
// ============================================================================

TimeZone::TimeZone(const std::string& id, int offset, bool hasDaylightTime) 
    : id_(id), offset_(offset), hasDaylightTime_(hasDaylightTime), valid_(true) {}

TimeZone TimeZone::utc() {
    return TimeZone("UTC", 0, false);
}

TimeZone TimeZone::systemTimeZone() {
#ifdef _WIN32
    TIME_ZONE_INFORMATION tzi;
    if (GetTimeZoneInformation(&tzi) == TIME_ZONE_ID_INVALID) {
        return utc();
    }
    
    int bias = tzi.Bias * 60; // 转换为秒
    bool hasDST = (GetTimeZoneInformation(&tzi) != TIME_ZONE_ID_UNKNOWN);
    
    return TimeZone("SYSTEM", bias, hasDST);
#else
    // Linux系统获取时区
    struct tm tm;
    time_t now = time(nullptr);
    localtime_r(&now, &tm);
    
    char buf[100];
    strftime(buf, sizeof(buf), "%Z", &tm);
    
    // 简单估算偏移，实际应该读取/etc/timezone等
    return TimeZone(buf, -tm.tm_gmtoff, tm.tm_isdst > 0);
#endif
}

TimeZone TimeZone::fromOffset(int offsetSeconds) {
    std::ostringstream oss;
    oss << "UTC" << (offsetSeconds >= 0 ? "+" : "") << (offsetSeconds / 3600);
    return TimeZone(oss.str(), offsetSeconds, false);
}

bool TimeZone::isDaylightTime(const DateTime& dt) const {
    // 简化实现，实际应该根据具体时区规则计算
    // 这里使用北美夏令时规则作为示例
    if (!hasDaylightTime_ || !dt.isValid()) {
        return false;
    }
    
    // 三月第二个星期日到十一月第一个星期日
    Date start(dt.year(), 3, 8 - dt.addDays(7 - dt.dayOfWeek()).dayOfWeek());
    Date end(dt.year(), 11, 1 + (7 - dt.addDays(1 - dt.dayOfWeek()).dayOfWeek()) % 7);
    
    return dt.date() >= start && dt.date() <= end;
}

std::vector<TimeZone> TimeZone::availableTimeZones() {
    // 简化实现，返回一些常见时区
    std::vector<TimeZone> zones;
    zones.push_back(utc());
    zones.push_back(fromOffset(28800));  // UTC+8 中国
    zones.push_back(fromOffset(-28800)); // UTC-8 美国西海岸
    zones.push_back(fromOffset(-18000)); // UTC-5 美国东海岸
    zones.push_back(fromOffset(3600));   // UTC+1 欧洲中部
    return zones;
}

// ============================================================================
// DateTime类实现
// ============================================================================

// 构造函数
DateTime::DateTime() : timeZone_(TimeZone::utc()) {}

DateTime::DateTime(const Date& date, const Time& time) 
    : date_(date), time_(time), timeZone_(TimeZone::utc()) {}

DateTime::DateTime(int year, int month, int day, int hour, int minute, int second, int msec) 
    : date_(year, month, day), time_(hour, minute, second, msec), timeZone_(TimeZone::utc()) {}

DateTime::DateTime(time_t timestamp) : timeZone_(TimeZone::utc()) {
    initFromTimestamp(static_cast<int64_t>(timestamp) * 1000, TimeZone::utc());
}

DateTime::DateTime(const struct tm& tm) 
    : date_(tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday), 
      time_(tm.tm_hour, tm.tm_min, tm.tm_sec, 0), 
      timeZone_(TimeZone::systemTimeZone()) {}

// 内部方法
void DateTime::initFromTimestamp(int64_t msecs, const TimeZone& zone) {
    // 从1970-01-01 00:00:00 UTC开始的毫秒数
    int64_t totalSecs = msecs / 1000;
    int msecPart = msecs % 1000;
    
    // 计算UTC日期和时间
    int daysSinceEpoch = static_cast<int>(totalSecs / 86400);
    int secsOfDay = static_cast<int>(totalSecs % 86400);
    
    // 创建UTC日期
    Date utcDate(Date::kJulianDayOf1970_01_01 + daysSinceEpoch);
    Time utcTime(secsOfDay / 3600, (secsOfDay % 3600) / 60, secsOfDay % 60, msecPart);
    
    // 根据时区偏移调整
    int offsetSeconds = zone.offsetFromUtc();
    int totalOffsetMsec = offsetSeconds * 1000;
    
    // 转换到目标时区
    Time localTime = utcTime.addMSecs(totalOffsetMsec);
    int dayAdjust = 0;
    
    if (localTime.msecsSinceStartOfDay() < totalOffsetMsec % 86400000) {
        dayAdjust = 1; // 跨天到下一天
    } else if (totalOffsetMsec < 0 && localTime.msecsSinceStartOfDay() > (86400000 + totalOffsetMsec) % 86400000) {
        dayAdjust = -1; // 跨天到前一天
    }
    
    date_ = utcDate.addDays(dayAdjust);
    time_ = localTime;
    timeZone_ = zone;
}

struct tm DateTime::toTM() const {
    struct tm tm = {0};
    tm.tm_year = date_.year() - 1900;
    tm.tm_mon = date_.month() - 1;
    tm.tm_mday = date_.day();
    tm.tm_hour = time_.hour();
    tm.tm_min = time_.minute();
    tm.tm_sec = time_.second();
    tm.tm_isdst = isDaylightTime() ? 1 : 0;
    return tm;
}

// 公共方法
DateTime DateTime::addYears(int years) const {
    if (!isValid()) {
        return DateTime();
    }
    return DateTime(date_.addYears(years), time_);
}

DateTime DateTime::addMonths(int months) const {
    if (!isValid()) {
        return DateTime();
    }
    return DateTime(date_.addMonths(months), time_);
}

DateTime DateTime::addDays(int days) const {
    if (!isValid()) {
        return DateTime();
    }
    return DateTime(date_.addDays(days), time_);
}

DateTime DateTime::addHours(int hours) const {
    if (!isValid()) {
        return DateTime();
    }
    
    int dayAdjust = hours / 24;
    int hourAdjust = hours % 24;
    
    Date newDate = date_.addDays(dayAdjust);
    Time newTime = time_.addHours(hourAdjust);
    
    if (newTime.hour() < time_.hour()) {
        newDate = newDate.addDays(1);
    }
    
    return DateTime(newDate, newTime);
}

DateTime DateTime::addMinutes(int minutes) const {
    if (!isValid()) {
        return DateTime();
    }
    
    int hourAdjust = minutes / 60;
    int minuteAdjust = minutes % 60;
    
    DateTime result = addHours(hourAdjust);
    Time newTime = result.time_.addMinutes(minuteAdjust);
    
    if (newTime.minute() < result.time_.minute()) {
        return DateTime(result.date_.addDays(1), newTime);
    }
    
    return DateTime(result.date_, newTime);
}

DateTime DateTime::addSecs(int seconds) const {
    if (!isValid()) {
        return DateTime();
    }
    
    int minuteAdjust = seconds / 60;
    int secondAdjust = seconds % 60;
    
    DateTime result = addMinutes(minuteAdjust);
    Time newTime = result.time_.addSecs(secondAdjust);
    
    if (newTime.second() < result.time_.second()) {
        return DateTime(result.date_.addDays(1), newTime);
    }
    
    return DateTime(result.date_, newTime);
}

DateTime DateTime::addMSecs(int msecs) const {
    if (!isValid()) {
        return DateTime();
    }
    
    int secondAdjust = msecs / 1000;
    int msecAdjust = msecs % 1000;
    
    DateTime result = addSecs(secondAdjust);
    Time newTime = result.time_.addMSecs(msecAdjust);
    
    if (newTime.msec() < result.time_.msec()) {
        return DateTime(result.date_.addDays(1), newTime);
    }
    
    return DateTime(result.date_, newTime);
}

int64_t DateTime::daysTo(const DateTime& other) const {
    if (!isValid() || !other.isValid()) {
        throw DateTimeError(DateTimeError::InvalidDate);
    }
    
    // 先转换到同一时区
    DateTime thisUTC = toUTC();
    DateTime otherUTC = other.toUTC();
    
    return thisUTC.date_.daysTo(otherUTC.date_);
}

int64_t DateTime::secsTo(const DateTime& other) const {
    if (!isValid() || !other.isValid()) {
        throw DateTimeError(DateTimeError::InvalidDate);
    }
    
    DateTime thisUTC = toUTC();
    DateTime otherUTC = other.toUTC();
    
    int64_t daysDiff = thisUTC.date_.daysTo(otherUTC.date_);
    int64_t secsDiff = thisUTC.time_.secsTo(otherUTC.time_);
    
    return daysDiff * 86400 + secsDiff;
}

int64_t DateTime::msecsTo(const DateTime& other) const {
    if (!isValid() || !other.isValid()) {
        throw DateTimeError(DateTimeError::InvalidDate);
    }
    
    return secsTo(other) * 1000 + (other.time_.msec() - time_.msec());
}

DateTime DateTime::toTimeZone(const TimeZone& zone) const {
    if (!isValid()) {
        return DateTime();
    }
    
    // 先转换到UTC
    DateTime utcTime = toUTC();
    
    // 计算UTC时间戳
    int64_t utcMsecs = utcTime.toMSecsSinceEpoch();
    
    // 应用新时区偏移
    DateTime result;
    result.initFromTimestamp(utcMsecs, zone);
    return result;
}

DateTime DateTime::toUTC() const {
    if (!isValid()) {
        return DateTime();
    }
    
    // 计算UTC时间戳
    int64_t localMsecs = toMSecsSinceEpoch();
    
    // 创建UTC时间
    DateTime result;
    result.initFromTimestamp(localMsecs, TimeZone::utc());
    return result;
}

DateTime DateTime::toLocalTime() const {
    return toTimeZone(TimeZone::systemTimeZone());
}

time_t DateTime::toTime_t() const {
    if (!isValid()) {
        return -1;
    }
    
    DateTime utcTime = toUTC();
    
    // 计算从1970-01-01开始的秒数
    int daysSinceEpoch = utcTime.date_.julianDay() - Date::kJulianDayOf1970_01_01;
    int secsOfDay = utcTime.time_.hour() * 3600 + utcTime.time_.minute() * 60 + utcTime.time_.second();
    
    return static_cast<time_t>(daysSinceEpoch * 86400 + secsOfDay);
}

int64_t DateTime::toMSecsSinceEpoch() const {
    if (!isValid()) {
        return -1;
    }
    
    DateTime utcTime = toUTC();
    
    // 计算从1970-01-01开始的毫秒数
    int daysSinceEpoch = utcTime.date_.julianDay() - Date::kJulianDayOf1970_01_01;
    int64_t msecsOfDay = static_cast<int64_t>(utcTime.time_.hour()) * 3600000 + 
                        static_cast<int64_t>(utcTime.time_.minute()) * 60000 + 
                        static_cast<int64_t>(utcTime.time_.second()) * 1000 + 
                        utcTime.time_.msec();
    
    return static_cast<int64_t>(daysSinceEpoch) * 86400000 + msecsOfDay;
}

std::string DateTime::toString(const std::string& format) const {
    if (!isValid()) {
        return "invalid-datetime";
    }
    
    std::string dateStr = date_.toString(format);
    std::string timeStr = time_.toString(format);
    
    // 简单的格式合并
    std::string result = format;
    
    // 替换日期部分
    size_t datePos = result.find("YYYY-MM-DD");
    if (datePos != std::string::npos) {
        result.replace(datePos, 10, date_.toISOString());
    }
    
    // 替换时间部分
    size_t timePos = result.find("HH:MM:SS");
    if (timePos != std::string::npos) {
        result.replace(timePos, 8, time_.toString("HH:MM:SS"));
    }
    
    return result;
}

std::string DateTime::toISOString() const {
    return toString("YYYY-MM-DD HH:MM:SS");
}

DateTime DateTime::currentDateTime() {
    DateTime result;
    
#ifdef _WIN32
    SYSTEMTIME st;
    GetLocalTime(&st);
    result = DateTime(st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
    result.timeZone_ = TimeZone::systemTimeZone();
#else
    struct timeval tv;
    gettimeofday(&tv, nullptr);
    time_t now = tv.tv_sec;
    struct tm* tm_now = localtime(&now);
    
    if (tm_now) {
        result = DateTime(tm_now->tm_year + 1900, tm_now->tm_mon + 1, tm_now->tm_mday, 
                         tm_now->tm_hour, tm_now->tm_min, tm_now->tm_sec, 
                         static_cast<int>(tv.tv_usec / 1000));
        result.timeZone_ = TimeZone::systemTimeZone();
    }
#endif
    
    return result;
}

DateTime DateTime::fromMSecsSinceEpoch(int64_t msecs, const TimeZone& zone) {
    DateTime result;
    result.initFromTimestamp(msecs, zone);
    return result;
}

DateTime DateTime::fromString(const std::string& str, DateFormat format) {
    // 简化实现，仅支持ISO格式
    if (format != DateFormat::ISODate) {
        return DateTime();
    }
    
    // 支持YYYY-MM-DD HH:MM:SS格式
    if (str.size() >= 19 && str[4] == '-' && str[7] == '-' && str[10] == ' ' && 
        str[13] == ':' && str[16] == ':') {
        
        try {
            int year = std::stoi(str.substr(0, 4));
            int month = std::stoi(str.substr(5, 2));
            int day = std::stoi(str.substr(8, 2));
            int hour = std::stoi(str.substr(11, 2));
            int minute = std::stoi(str.substr(14, 2));
            int second = std::stoi(str.substr(17, 2));
            int msec = 0;
            
            // 可选的毫秒部分
            if (str.size() > 19 && str[19] == '.') {
                std::string msecStr = str.substr(20, 3);
                msec = std::stoi(msecStr);
            }
            
            return DateTime(year, month, day, hour, minute, second, msec);
        } catch (...) {
            return DateTime();
        }
    }
    
    return DateTime();
}

bool DateTime::operator==(const DateTime& other) const {
    return toMSecsSinceEpoch() == other.toMSecsSinceEpoch();
}

bool DateTime::operator!=(const DateTime& other) const {
    return toMSecsSinceEpoch() != other.toMSecsSinceEpoch();
}

bool DateTime::operator<(const DateTime& other) const {
    return toMSecsSinceEpoch() < other.toMSecsSinceEpoch();
}

bool DateTime::operator<=(const DateTime& other) const {
    return toMSecsSinceEpoch() <= other.toMSecsSinceEpoch();
}

bool DateTime::operator>(const DateTime& other) const {
    return toMSecsSinceEpoch() > other.toMSecsSinceEpoch();
}

bool DateTime::operator>=(const DateTime& other) const {
    return toMSecsSinceEpoch() >= other.toMSecsSinceEpoch();
}

// ============================================================================
// DateTimeUtils类实现
// ============================================================================

int DateTimeUtils::weekNumber(int year, int month, int day) {
    Date date(year, month, day);
    if (!date.isValid()) {
        return -1;
    }
    
    // 计算本年第一天
    Date firstDay(year, 1, 1);
    int firstDayWeek = firstDay.dayOfWeek();
    
    // 计算与第一天的天数差
    int daysDiff = date.daysTo(firstDay);
    
    // 计算周数
    int weekNum = (daysDiff + firstDayWeek - 1) / 7 + 1;
    
    // 处理跨年情况
    if (weekNum <= 0) {
        return weekNumber(year - 1, 12, 31);
    } else if (weekNum > 53) {
        return 1;
    }
    
    return weekNum;
}

bool DateTimeUtils::isValidDate(int year, int month, int day) {
    if (year < 1 || year > 9999 || month < 1 || month > 12 || day < 1) {
        return false;
    }
    
    // 检查每月的天数
    static const int daysInMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int maxDays = daysInMonth[month];
    
    if (month == 2 && isLeapYear(year)) {
        maxDays = 29;
    }
    
    return day <= maxDays;
}

bool DateTimeUtils::isValidTime(int hour, int minute, int second, int msec) {
    return hour >= 0 && hour < 24 && 
           minute >= 0 && minute < 60 && 
           second >= 0 && second < 60 && 
           msec >= 0 && msec < 1000;
}

int DateTimeUtils::daysInMonth(int year, int month) {
    static const int daysInMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    
    if (month < 1 || month > 12) {
        return 0;
    }
    
    if (month == 2 && isLeapYear(year)) {
        return 29;
    }
    
    return daysInMonth[month];
}

bool DateTimeUtils::isLeapYear(int year) {
    // 闰年规则：能被4整除但不能被100整除，或能被400整除
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

// ============================================================================
// Rate类实现
// ============================================================================

Rate::Rate(float frequency) : startTime_(DateTime::currentDateTime()) {
    reset(frequency);
}

void Rate::reset(float frequency) {
    if (frequency <= 0) {
        frequency = 1.0f;
    }
    
    // 计算时间间隔（微秒）
    int64_t microSeconds = static_cast<int64_t>(1000000.0f / frequency);
    interval_ = std::chrono::microseconds(microSeconds);
    startTime_ = DateTime::currentDateTime();
}

bool Rate::sleep() {
    DateTime now = DateTime::currentDateTime();
    int64_t elapsed = startTime_.msecsTo(now);
    int64_t expectedInterval = interval_.count() / 1000; // 转换为毫秒
    
    if (elapsed < expectedInterval) {
        int64_t sleepTime = expectedInterval - elapsed;
        
#ifdef _WIN32
        Sleep(static_cast<DWORD>(sleepTime));
#else
        usleep(static_cast<useconds_t>(sleepTime * 1000));
#endif
        
        startTime_ = startTime_.addMSecs(expectedInterval);
        return true;
    }
    
    startTime_ = now;
    return false;
}

bool Rate::wakeup(float sigma) {
    DateTime now = DateTime::currentDateTime();
    int64_t elapsed = startTime_.msecsTo(now);
    int64_t expectedInterval = interval_.count() / 1000; // 转换为毫秒
    
    // 计算随机偏移
    int64_t jitter = 0;
    if (sigma > 0) {
        // 简单的高斯分布模拟
        float random = static_cast<float>(rand()) / RAND_MAX * 2.0f - 1.0f;
        jitter = static_cast<int64_t>(random * sigma * expectedInterval);
    }
    
    int64_t adjustedInterval = expectedInterval + jitter;
    
    if (elapsed < adjustedInterval) {
        int64_t sleepTime = adjustedInterval - elapsed;
        
#ifdef _WIN32
        Sleep(static_cast<DWORD>(sleepTime));
#else
        usleep(static_cast<useconds_t>(sleepTime * 1000));
#endif
        
        startTime_ = startTime_.addMSecs(adjustedInterval);
        return true;
    }
    
    startTime_ = now;
    return false;
}

} // namespace cytoolkit